package com.zhxx.book.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhxx.book.entity.Course;
import com.zhxx.book.entity.Teacher;
import com.zhxx.book.service.ICourseService;
import com.zhxx.book.service.ITeacherService;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: 课程
 * @Author Alex
 * @Date 2022-11-14 11:17
 */
@RestController
@RequestMapping("/course")
public class CourseController {
   @Autowired
   private ICourseService courseService;
   @Autowired
   private ITeacherService teacherService;

   @GetMapping
   public List<Course> list() {
      return getCourses(null);
   }

   @GetMapping("/type/{type}")
   public List<Course> getByType(@PathVariable("type") int type) {
      return getCourses(type);
   }

   // type: 1 小班课，2 1对1
   private List<Course> getCourses(Integer type) {
      // type: 1 小班课，2 1对1
      LambdaQueryWrapper<Course> queryWrapper = Wrappers.lambdaQuery();
      queryWrapper.eq(type != null, Course::getType, type)
         .orderByDesc(Course::getStartTime);
      List<Teacher> teacherList = teacherService.list();
      return courseService.list(queryWrapper).stream().peek(item -> {
         Teacher teacher = teacherList.stream()
            .filter(t -> Objects.equals(t.getId(), item.getTeacherId()))
            .findFirst()
            .orElse(new Teacher());
         item.setTeacherName(teacher.getName());
      }).collect(Collectors.toList());
   }

   @PostMapping
   public Boolean add(@RequestBody Course course) {
      return courseService.save(course);
   }

   @PutMapping
   public Boolean update(@RequestBody Course course) {
      return courseService.updateById(course);
   }

   @DeleteMapping("/{id}")
   public Boolean delete(@PathVariable Long id) {
      return courseService.removeById(id);
   }
}
